package com.mnkjxy.beauty.net.protocal;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.xmlpull.v1.XmlSerializer;

import android.annotation.SuppressLint;
import android.util.Log;

public class Header {

	private static final String TAG = "Header";
	/**
	 * 请求唯一标示
	 */
	private Leaf messengerid = new Leaf("messengerid");
	/**
	 * 时间戳
	 */
	private Leaf timestamp = new Leaf("timestamp");
	/**
	 * 明文完整body md5加密
	 */
	private Leaf digest = new Leaf("digest");
	/**
	 * 请求类型
	 */
	private Leaf Transactiontype = new Leaf("Transactiontype");
	/**
	 * 用户名
	 */
	private Leaf username = new Leaf("username");

	/**
	 * @param serializer
	 */
	@SuppressLint("SimpleDateFormat")
	public void serializerHeader(XmlSerializer serializer, String body) {
		// 时间格式化
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
		String date = dateFormat.format(new Date());
		timestamp.setTagValue(date);

		// 请求id
		Random random = new Random();
		int num = random.nextInt(999999) + 1;
		DecimalFormat format = new DecimalFormat("000000");
		String ranNum = format.format(num);
		messengerid.setTagValue(date + ranNum);

		// 请求的文本摘要 body明文采用md5加密
		String digestInfo;
		try {
			digestInfo = DigestUtils.md5Hex(body.getBytes("utf-8"));

			digest.setTagValue(digestInfo);
			Log.i(TAG, "md5值为 --" + digestInfo);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			serializer.startTag(null, "header");

			timestamp.serializerLeaf(serializer);
			messengerid.serializerLeaf(serializer);
			digest.serializerLeaf(serializer);
			Transactiontype.serializerLeaf(serializer);
			username.serializerLeaf(serializer);

			serializer.endTag(null, "header");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 每个请求必须使用,设置请求类型
	 * 
	 * @return
	 */
	public Leaf getTransactiontype() {
		return Transactiontype;
	}

	/**
	 * 每个请求不许使用,设置请求用户名
	 * 
	 * @return
	 */
	public Leaf getUsername() {
		return username;
	}

}
